#include "cam.h"
#include "X264_Code.h"
#include "RTMP.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define ServerURL "rtmp://10.7.178.63:9090/live"

int main(int argc, char *argv[])
{
	// 初始化摄像头
	unsigned int size1;
	unsigned int width = 640, height = 480, ismjpeg = 0;
	int cam_fd = camera_init(CAMERA_USB, &width, &height, &size1, &ismjpeg);
	if (cam_fd < 0)
	{
		printf("camera_init\n");
		return -1;
	}

	// 初始化编码器
	Encode en;
	sps_pps sp;
	int ret = X264_Iinit(&en, &sp);
	if (ret < 0)
	{
		printf("X264_Iinit\n");
		camera_exit(cam_fd);
		return -1;
	}
	// 初始化RTMP
	RTMP *r = NULL;
	int connect = RTMP_ConnectNginx(&r, ServerURL);
	if (connect < 0)
	{
		printf("RTMP_ConnectNginx erro\n");
		camera_exit(cam_fd);
		return -1;
	}

	// 开启摄像头
	ret = camera_start(cam_fd);
	if (ret < 0)
	{
		printf("camera_start\n");
		camera_exit(cam_fd);
		return -1;
	}

	unsigned char *cam_buf = NULL; // 摄像头图像的指针
	int size = 0;
	unsigned int index = 0;
	// 循环采集图像并编码
	while (1)
	{
		int nal_num = 0;
		// 出队帧数据并赋值到cam_buf
		camera_dqbuf(cam_fd, (void **)&cam_buf, &size, &index);
		// 入队
		camera_eqbuf(cam_fd, index);
		// 编码
		X264_Encode(&en, cam_buf, &nal_num);
		if (nal_num > 0)
		{
			for (int i = 0; i < nal_num; i++)
			{
				// 如果是关键帧，先发SPS+PPS再发IDR，如果是非关键帧，我就可以直接发
				if (en.nal[i].i_type == NAL_SLICE || en.nal[i].i_type == NAL_SLICE_IDR)
				{
					// 关键帧
					RTMP_SendSpsPacket(r, &sp); // 发送SPS+PPS   0x00 00  00  00 01
					RTMPSend_H264_Packet(r, en.nal[i].p_payload + 4, en.nal[i].i_payload - 4, 1);
				}
				else
				{
					RTMPSend_H264_Packet(r, en.nal[i].p_payload + 4, en.nal[i].i_payload - 4, 0);
				}
			}
		}
	}

	camera_stop(cam_fd);
	camera_exit(cam_fd);
	// 释放资源
	X264_Release(&en, &sp);

	return 0;
}
